package com.example.service;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * Author wangJinLong
 * Date 2025/11/19 14:40
 **/
@Service
public class EmailService {

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 发送带附件的邮件
     * @param from        发件人邮箱，必填
     * @param to          收件人邮箱，必填
     * @param subject     邮件主题，必填
     * @param content     邮件正文（支持 HTML），必填
     */
    public void sendEmailToMyself(String from, String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);       // 必须和配置的 username 一致
        message.setTo(to);         // 收件人（可以是自己）
        message.setSubject(subject);
        message.setText(content);
        javaMailSender.send(message);
    }

    /**
     * 发送带附件的邮件
     * @param from        发件人邮箱，必填
     * @param to          收件人邮箱，必填
     * @param subject     邮件主题，必填
     * @param content     邮件正文（支持 HTML），必填
     * @param attachment  附件文件（File 对象）
     * @param fileName    附件在邮件中显示的名称（可选）
     */
    public void sendEmailWithAttachment(
            String from,
            String to,
            String subject,
            String content,
            File attachment,
            String fileName) throws MessagingException {

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // multipart = true 表示启用多部分（文本+附件）
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");

        helper.setFrom(from); // 必须与配置的 username 一致
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true); // true 表示内容是 HTML

        // 添加附件
        if (attachment != null && attachment.exists()) {
            // 如果未指定 fileName，则使用原文件名
            String attachName = (fileName != null) ? fileName : attachment.getName();
            helper.addAttachment(attachName, attachment);
        }

        javaMailSender.send(mimeMessage);
    }
}
